package com.huixixi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huixixi.common.R;
import com.huixixi.entity.Category;
import com.huixixi.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("菜品分类新增成功");
    }


    /**
     * 分页查询功能
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();

        //添加排序条件
        queryWrapper.orderByDesc(Category::getSort);
        //执行查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);

    }


    /**
     * 根据id删除菜品分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
//        categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("菜品分类删除成功");
    }


    /**
     * 根据id修改分类信息
     *
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("分类信息修改成功");
    }


    /**
     * 根据条件查询菜品分类
     *
     * @param category
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        //添加条件   菜品分类不为空，将数据库中的菜品分类，赋值传给页面
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());

        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort);

        //数据库查询到所有的分类集合封装传给前端页面
        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }

}
